<template>
  <div class="page-content">
    <div class="header">
      <h3>套餐管理</h3>
    </div>

    <div class="filter-bar">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-select v-model="selectedVipId" placeholder="选择VIP等级" @change="handleVipChange">
            <el-option
              v-for="vip in vipLevels"
              :key="vip.id"
              :label="vip.vip_name"
              :value="vip.id.toString()"
            />
          </el-select>
        </el-col>
        <el-col :span="12" class="action-buttons">
          <el-button type="primary" @click="addPackage" v-ripple>添加安卓套餐</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 套餐列表 -->
    <package-list
      :package-list="packageList"
      :loading="loading"
      @add-package="addPackageToSystem"
      @delete-system="deleteSystemPackage"
      @edit-package="editPackage"
      @remove-package="removePackage"
    />
    
    <!-- 套餐编辑/添加对话框 -->
    <package-dialog
      v-model="packageDialogVisible"
      :form="packageForm"
      :is-edit="isEdit"
      :current-system-package="currentSystemPackage"
      :vip-levels="vipLevels"
      :android-versions="androidVersions"
      :android-version-total="androidVersionTotal"
      :android-versions-loading="androidVersionsLoading"
      @fetch-android-versions="fetchAndroidVersions(1)"
      @load-more-android-versions="loadMoreAndroidVersions"
      @save="savePackage"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getVipLevels, 
  getPackageList, 
  addPackage as addPackageApi,
  updatePackage as updatePackageApi, 
  deletePackage as deletePackageApi,
  getAndroidVersionList,
  type AndroidVersion,
  type AddPackageParams 
} from '@/Newapi/device'

// 导入组件
import PackageList from './components/PackageList.vue'
import PackageDialog from './components/PackageDialog.vue'

// 定义接口
interface VipLevel {
  id: number
  created_at: string
  updated_at: string
  vip_name: string
  level: number
}

interface PriceInfo {
  [key: string]: number
}

interface Package {
  activate_name: string
  actually_package_id: number
  day: number
  origin_price: number
  price: PriceInfo
  renew_display: boolean
  tag: string
  title: string
}

interface SystemPackage {
  id: number
  system_version_name: string
  vip_level: string
  activate_package: Package[]
}

// 状态变量
const loading = ref(false)
const vipLevels = ref<VipLevel[]>([])
const packageList = ref<SystemPackage[]>([])
const selectedVipId = ref('')

// 表单相关
const packageDialogVisible = ref(false)
const isEdit = ref(false)
const packageForm = reactive({
  title: '',
  day: 1,
  origin_price: 0,
  tag: '',
  activate_name: '',
  renew_display: false,
  actually_package_id: 0,
  vip_level: '', // 新增VIP等级字段
  system_version: '', // 新增系统类型字段
  price_tiers: [
    { range_start: 1, range_end: 5 as number | undefined, price: 0 },
    { range_start: 5, range_end: 30 as number | undefined, price: 0 },
    { range_start: 30, range_end: undefined as number | undefined, price: 0 }
  ]
})

// 添加安卓版本状态变量
const androidVersions = ref<AndroidVersion[]>([])
const androidVersionsLoading = ref(false)
const androidVersionPage = ref(1)
const androidVersionTotal = ref(0)

// 添加新的状态变量
const currentSystemPackage = ref<SystemPackage | null>(null)

// 初始化
onMounted(async () => {
  await Promise.all([fetchVipLevels(), fetchAndroidVersions(1)])
  if (vipLevels.value.length > 0) {
    selectedVipId.value = vipLevels.value[0].id.toString()
    await fetchPackages()
  }
})

// 获取VIP等级列表
const fetchVipLevels = async () => {
  loading.value = true
  try {
    const res = await getVipLevels()
    if (res.code === 200) {
      vipLevels.value = res.data || [] // 处理data为null的情况
    } else {
      ElMessage.error(res.msg || '获取VIP等级失败')
    }
  } catch (error) {
    console.error('获取VIP等级列表失败:', error)
    ElMessage.error('获取VIP等级列表失败')
  } finally {
    loading.value = false
  }
}

// 获取安卓版本列表
const fetchAndroidVersions = async (page = 1) => {
  androidVersionsLoading.value = true
  try {
    const res = await getAndroidVersionList({
      page,
      pageSize: 10
    })
    
    if (res.code === 200) {
      if (page === 1) {
        androidVersions.value = res.data?.list || []
      } else {
        androidVersions.value.push(...(res.data?.list || []))
      }
      androidVersionPage.value = res.data?.page || 1
      androidVersionTotal.value = res.data?.total || 0
    } else {
      ElMessage.error(res.msg || '获取安卓版本列表失败')
    }
  } catch (error) {
    console.error('获取安卓版本列表失败:', error)
    ElMessage.error('获取安卓版本列表失败')
  } finally {
    androidVersionsLoading.value = false
  }
}

// 加载更多安卓版本
const loadMoreAndroidVersions = () => {
  if (androidVersions.value.length < androidVersionTotal.value && !androidVersionsLoading.value) {
    fetchAndroidVersions(androidVersionPage.value + 1)
  }
}

// 获取套餐列表
const fetchPackages = async () => {
  if (!selectedVipId.value) {
    ElMessage.warning('请先选择VIP等级')
    return
  }
  
  loading.value = true
  try {
    const res = await getPackageList({
      vip_level: selectedVipId.value,
      side: "-1"
    })
    
    if (res.code === 200) {
      packageList.value = res.data || [] // 处理data为null的情况
    } else {
      ElMessage.error(res.msg || '获取套餐列表失败')
    }
  } catch (error) {
    console.error('获取套餐列表失败:', error)
    ElMessage.error('获取套餐列表失败')
  } finally {
    loading.value = false
  }
}

// 处理VIP等级变更
const handleVipChange = () => {
  fetchPackages()
}

// 添加套餐
const addPackage = () => {
  isEdit.value = false
  currentSystemPackage.value = null // 确保添加新套餐时，currentSystemPackage为null
  
  // 确保有安卓版本数据
  if (androidVersions.value.length === 0) {
    fetchAndroidVersions(1)
  }
  
  // 重置表单 - 使用直接设置属性的方式
  packageForm.title = ''
  packageForm.day = 1
  packageForm.origin_price = 0
  packageForm.tag = ''
  packageForm.activate_name = ''
  packageForm.renew_display = false
  packageForm.actually_package_id = 0
  packageForm.vip_level = '' // 重置VIP等级
  packageForm.system_version = '' // 重置系统类型
  
  // 使用setTimeout来避免同步的响应式更新循环
  setTimeout(() => {
    packageForm.price_tiers = [
      { range_start: 1, range_end: 5 as number | undefined, price: 0 },
      { range_start: 5, range_end: 30 as number | undefined, price: 0 },
      { range_start: 30, range_end: undefined as number | undefined, price: 0 }
    ]
    
    // 在修改完所有属性后再显示对话框
    packageDialogVisible.value = true
  }, 0)
}

// 编辑套餐
const editPackage = (pkg: Package) => {
  isEdit.value = true
  
  // 将已有的价格转换为表单中的价格梯度格式
  const priceTiers: { range_start: number, range_end?: number, price: number }[] = []
  for (const [range, price] of Object.entries(pkg.price)) {
    if (range.includes('~')) {
      const [start, end] = range.split('~').map(num => parseInt(num.trim()))
      priceTiers.push({ range_start: start, range_end: end, price: parseInt(price as any) })
    } else {
      // 单个数字如 "30": 255 表示大于等于30
      priceTiers.push({ range_start: parseInt(range), range_end: undefined, price: parseInt(price as any) })
    }
  }
  
  // 确保有安卓版本数据
  if (androidVersions.value.length === 0) {
    fetchAndroidVersions(1)
  }
  
  // 查找当前套餐所属的系统包
  const systemPackage = packageList.value.find(system => 
    system.activate_package.some(p => p.actually_package_id === pkg.actually_package_id)
  )
  
  if (!systemPackage) {
    ElMessage.error('未找到套餐所属的系统版本')
    return
  }
  
  // 保存当前系统包信息，用于更新时使用
  currentSystemPackage.value = systemPackage
  
  // 从系统版本名称中提取ID
  let systemVersionId = ''
  // 尝试根据系统版本名查找对应的安卓版本ID
  const versionName = systemPackage.system_version_name
  const matchedVersion = androidVersions.value.find(v => v.android_name === versionName)
  if (matchedVersion) {
    systemVersionId = matchedVersion.id.toString()
  }
  
  // 填充表单 - 修改为直接设置属性，避免响应式对象的递归更新
  packageForm.title = pkg.title
  packageForm.day = pkg.day
  packageForm.origin_price = pkg.origin_price
  packageForm.tag = pkg.tag
  packageForm.activate_name = pkg.activate_name || ''
  packageForm.renew_display = pkg.renew_display
  packageForm.actually_package_id = pkg.actually_package_id
  packageForm.vip_level = selectedVipId.value  // 设置为当前页面选择的VIP等级
  packageForm.system_version = systemVersionId // 设置为匹配的安卓版本ID
  
  // 使用setTimeout来避免同步的响应式更新循环
  setTimeout(() => {
    packageForm.price_tiers = priceTiers.length > 0 
      ? JSON.parse(JSON.stringify(priceTiers)) 
      : [{ range_start: 1, range_end: undefined, price: 0 }]
    
    // 在修改完所有属性后再显示对话框
    packageDialogVisible.value = true
  }, 0)
}

// 删除单个套餐
const removePackage = (pkg: Package) => {
  ElMessageBox.confirm(`确定要删除套餐 "${pkg.title}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      
      // 查找当前套餐所属的系统包
      const systemPackage = packageList.value.find(system => 
        system.activate_package.some(p => p.actually_package_id === pkg.actually_package_id)
      )
      
      if (!systemPackage) {
        ElMessage.error('未找到套餐所属的系统版本')
        return
      }
      
      // 获取所有小套餐并移除要删除的套餐
      const remainingPackages = systemPackage.activate_package.filter(p => 
        p.actually_package_id !== pkg.actually_package_id
      )
      
      // 查找匹配的系统版本ID
      const matchedVersion = androidVersions.value.find(v => 
        v.android_name === systemPackage.system_version_name
      )
      
      // 查找匹配的VIP等级ID
      const matchedVip = vipLevels.value.find(v => 
        v.vip_name === systemPackage.vip_level
      )
      
      if (!matchedVersion) {
        ElMessage.error('无法匹配系统版本，请重新加载页面')
        return
      }
      
      if (!matchedVip) {
        ElMessage.error('无法匹配VIP等级，请重新加载页面')
        return
      }
      
      // 构建完整的更新数据
      const updateData = {
        id: systemPackage.id,
        system_version: matchedVersion.id,
        vip_level: matchedVip.id,
        activate_package: remainingPackages
      }
      
      // 调用更新API
      const res = await updatePackageApi(updateData)
      
      if (res.code === 200) {
        ElMessage.success('套餐已删除')
        // 如果删除的是最后一个子套餐，可能需要刷新整个列表
        fetchPackages()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除套餐出错:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 添加新的方法，用于向已有系统添加套餐
const addPackageToSystem = (systemPackage: SystemPackage) => {
  isEdit.value = false
  currentSystemPackage.value = systemPackage
  
  // 确保有安卓版本数据
  if (androidVersions.value.length === 0) {
    fetchAndroidVersions(1)
  }
  
  // 重置表单 - 使用直接赋值方式
  packageForm.title = ''
  packageForm.day = 1
  packageForm.origin_price = 0
  packageForm.tag = ''
  packageForm.activate_name = ''
  packageForm.renew_display = false
  packageForm.actually_package_id = 0
  packageForm.vip_level = '' // 重置VIP等级
  packageForm.system_version = '' // 重置系统类型
  
  // 从系统版本名称中提取ID
  let systemVersionId = ''
  // 尝试根据系统版本名查找对应的安卓版本ID
  const versionName = systemPackage.system_version_name
  const matchedVersion = androidVersions.value.find(v => v.android_name === versionName)
  if (matchedVersion) {
    systemVersionId = matchedVersion.id.toString()
  }
  
  // 查找匹配的VIP等级ID
  const vipLevelName = systemPackage.vip_level
  const matchedVip = vipLevels.value.find(v => v.vip_name === vipLevelName)
  
  // 设置VIP等级和系统版本
  if (matchedVip) {
    packageForm.vip_level = matchedVip.id.toString()
  }
  
  if (systemVersionId) {
    packageForm.system_version = systemVersionId
  }
  
  // 使用setTimeout异步设置价格梯度和显示对话框
  setTimeout(() => {
    packageForm.price_tiers = [
      { range_start: 1, range_end: 5 as number | undefined, price: 0 },
      { range_start: 5, range_end: 30 as number | undefined, price: 0 },
      { range_start: 30, range_end: undefined as number | undefined, price: 0 }
    ]
    
    packageDialogVisible.value = true
  }, 0)
}

// 修改保存套餐的函数
const savePackage = async () => {
  // 表单验证
  if (!packageForm.vip_level) {
    ElMessage.warning('请选择VIP等级')
    return
  }
  
  if (!packageForm.system_version) {
    ElMessage.warning('请选择系统版本')
    return
  }
  
  if (packageForm.day <= 0) {
    ElMessage.warning('有效期必须大于0天')
    return
  }
  
  if (packageForm.origin_price < 0) {
    ElMessage.warning('原价不能为负数')
    return
  }
  
  // 验证价格梯度
  let hasPriceTier = false
  for (const tier of packageForm.price_tiers) {
    if (tier.price < 0) {
      ElMessage.warning('价格梯度的价格不能为负数')
      return
    }
    
    if (tier.price > 0) {
      hasPriceTier = true
    }
  }
  
  if (!hasPriceTier) {
    ElMessage.warning('至少需要设置一个有效的价格梯度')
    return
  }

  try {
    loading.value = true
    
    // 转换价格梯度为API需要的格式
    const price: Record<string, number> = {}
    packageForm.price_tiers.forEach((tier, index) => {
      if (tier.range_end && index < packageForm.price_tiers.length - 1) {
        price[`${tier.range_start}~${tier.range_end}`] = tier.price
      } else {
        price[`${tier.range_start}`] = tier.price
      }
    })
    
    let res;
    
    if (isEdit.value) {
      // 如果是编辑模式
      if (!currentSystemPackage.value) {
        ElMessage.error('系统套餐信息不完整，无法更新')
        return
      }
      
      // 获取所有小套餐
      const allPackages = [...currentSystemPackage.value.activate_package]
      
      // 找到要修改的套餐索引
      const packageIndex = allPackages.findIndex(p => p.actually_package_id === packageForm.actually_package_id)
      
      if (packageIndex === -1) {
        ElMessage.error('未找到要编辑的套餐')
        return
      }
      
      // 创建更新的套餐对象
      const updatedPackage = {
        day: packageForm.day,
        tag: packageForm.tag,
        price: price,
        title: packageForm.title,
        origin_price: packageForm.origin_price,
        activate_name: packageForm.activate_name,
        renew_display: packageForm.renew_display,
        actually_package_id: packageForm.actually_package_id
      }
      
      // 更新数组中对应的套餐
      allPackages[packageIndex] = updatedPackage
      
      // 查找匹配的系统版本ID
      const matchedVersion = androidVersions.value.find(v => 
        v.android_name === currentSystemPackage.value?.system_version_name
      )
      
      // 查找匹配的VIP等级ID
      const matchedVip = vipLevels.value.find(v => 
        v.vip_name === currentSystemPackage.value?.vip_level
      )
      
      if (!matchedVersion) {
        ElMessage.error('无法匹配系统版本，请重新加载页面')
        return
      }
      
      if (!matchedVip) {
        ElMessage.error('无法匹配VIP等级，请重新加载页面')
        return
      }
      
      // 构建完整的更新数据
      const updateData = {
        id: currentSystemPackage.value.id,
        system_version: matchedVersion.id,
        vip_level: matchedVip.id,
        activate_package: allPackages
      }
      
      // 调用更新API
      res = await updatePackageApi(updateData)
    } else if (currentSystemPackage.value) {
      // 如果是向已有系统添加套餐
      // 获取所有小套餐
      const allPackages = [...currentSystemPackage.value.activate_package]
      
      // 创建新套餐对象
      const newPackage = {
        day: packageForm.day,
        tag: packageForm.tag,
        price: price,
        title: packageForm.title,
        origin_price: packageForm.origin_price,
        activate_name: packageForm.activate_name,
        renew_display: packageForm.renew_display,
        actually_package_id: Date.now() // 使用时间戳作为ID
      }
      
      // 添加到套餐列表
      allPackages.push(newPackage)
      
      // 查找匹配的系统版本ID
      const matchedVersion = androidVersions.value.find(v => 
        v.android_name === currentSystemPackage.value?.system_version_name
      )
      
      // 查找匹配的VIP等级ID
      const matchedVip = vipLevels.value.find(v => 
        v.vip_name === currentSystemPackage.value?.vip_level
      )
      
      if (!matchedVersion) {
        ElMessage.error('无法匹配系统版本，请重新加载页面')
        return
      }
      
      if (!matchedVip) {
        ElMessage.error('无法匹配VIP等级，请重新加载页面')
        return
      }
      
      // 构建完整的更新数据
      const updateData = {
        id: currentSystemPackage.value.id,
        system_version: matchedVersion.id,
        vip_level: matchedVip.id,
        activate_package: allPackages
      }
      
      // 调用更新API
      res = await updatePackageApi(updateData)
    } else {
      // 如果是添加全新的套餐
      const packageData = {
        system_version: parseInt(packageForm.system_version),
        vip_level: parseInt(packageForm.vip_level),
        activate_package: [{
          day: packageForm.day,
          tag: packageForm.tag,
          price: price,
          title: packageForm.title,
          origin_price: packageForm.origin_price,
          activate_name: packageForm.activate_name,
          renew_display: packageForm.renew_display,
          actually_package_id: Date.now() // 使用时间戳作为ID
        }]
      }
      
      // 调用添加API
      res = await addPackageApi(packageData)
    }
    
    if (res.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
      packageDialogVisible.value = false
      fetchPackages()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error(isEdit.value ? '更新套餐出错:' : '添加套餐出错:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 添加删除整个系统套餐的方法
const deleteSystemPackage = (systemPackage: SystemPackage) => {
  ElMessageBox.confirm(`确定要删除"${systemPackage.system_version_name} - ${systemPackage.vip_level}"套餐及其所有子套餐吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      
      // 调用删除API
      const res = await deletePackageApi(systemPackage.id)
      
      if (res.code === 200) {
        ElMessage.success('套餐已删除')
        // 重新获取套餐列表
        fetchPackages()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除系统套餐出错:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消删除
  })
}
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .header {
    padding-bottom: 15px;
    border-bottom: 1px solid var(--art-border-color);

    h3 {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .filter-bar {
    margin: 20px 0;
    
    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
    }
  }
}
</style> 